import { Checkbox, Row, Col, Divider, message, Radio, Form } from "antd";
import { useReactive } from "ahooks";
import { useEffect } from "react";
import { useModel } from "umi";
import { AllMembers, FindTaskInfo, CreateTaskInfo } from "../../_graphql/tasks";
import { Button } from "@douyinfe/semi-ui";

const layout = { labelCol: { span: 6 }, wrapperCol: { span: 16 } };
const tailLayout = { wrapperCol: { offset: 6, span: 16 } };

const SetSceneMembers = ({ application, taskKey, taskInfo, taskMembers, reloadData }) => {
    const { graphqlFetch } = useModel("global");
    const { onCloseGlobalModal } = useModel("global.modal");
    const [form] = Form.useForm();

    const state = useReactive({
        loading: false,
        members: [],
        selectMember: null,
        selectTaskScene: [],
    });

    const loadMembers = async () => {
        let res = await graphqlFetch({ query: AllMembers, variables: {} });
        state.members = res?.a?.nodes || [];
    };

    const loadTaskScene = async () => {
        let taskScene = [];
        Object.values(taskInfo.versions).map((item) => {
            if (item.isSet) taskScene.push(item);
        });
        state.selectTaskScene = taskScene;
        let obj = {};
        let arr = [];
        taskMembers.map((item) =>
            state.selectTaskScene.map((_item) => {
                if (item.atRona === _item.label) {
                    if (_item.isMany) {
                        arr.push(item.omUuid);
                        obj[item.atRona] = arr;
                    } else {
                        obj[item.atRona] = item.omUuid;
                    }
                }
            })
        );
        form.setFieldsValue(obj);
        state.selectMember = obj;
    };

    useEffect(() => {
        loadMembers();
    }, []);

    useEffect(() => {
        loadTaskScene();
    }, []);

    const onFinish = async (values) => {
        let createOrUpdateTaskMembers = ``,
            deteleTaskMembers = ``;
        let res = await graphqlFetch({ query: FindTaskInfo, variables: { aiUuid: application.aiUuid, atName: taskKey, atVenu: taskInfo.default } }, "wulian");
        if (res?.a?.nodes?.length === 0) {
            let res = await graphqlFetch({
                query: CreateTaskInfo,
                variables: {
                    aiUuid: application.aiUuid,
                    atName: taskKey,
                    atVenu: taskInfo.default,
                    atCont: taskInfo.content,
                },
            });
            if (!res) {
                message.warning("创建任务版本失败！");
                onCloseGlobalModal();
            }
        }
        if (Object.values(values).every((item) => item === undefined)) return message.warn("请选择任务成员再提交！");
        if (state.selectMember) {
            Object.keys(state.selectMember).map((item, index) => {
                if (state.selectMember[item]) {
                    if (Array.isArray(state.selectMember[item])) {
                        state.selectMember[item].map((_item, i) => {
                            deteleTaskMembers += `${"b" + index + i}:deleteApplicationTaskSceneRolesMemberByAiUuidAndAtNameAndAtVenuAndOmUuidAndAtRona(
                                input: {aiUuid: "${application.aiUuid}", atName: "${taskKey}", omUuid: "${_item}", atRona: "${item}", atVenu: "${
                                    taskInfo.default
                                }"}
                            ) { clientMutationId }`;
                        });
                    } else {
                        deteleTaskMembers += `${"b" + index}:deleteApplicationTaskSceneRolesMemberByAiUuidAndAtNameAndAtVenuAndOmUuidAndAtRona(
                            input: {aiUuid: "${application.aiUuid}", atName: "${taskKey}", omUuid: "${state.selectMember[item]}", atRona: "${item}", atVenu: "${
                                taskInfo.default
                            }"}
                        ) { clientMutationId }`;
                    }
                }
            });
        }
        Object.keys(values).map((item, index) => {
            if (values[item]) {
                if (Array.isArray(values[item])) {
                    if (values[item].length > 0) {
                        values[item].map((_item, i) => {
                            createOrUpdateTaskMembers += `${"a" + index + i}:createApplicationTaskSceneRolesMember(
                                    input: {applicationTaskSceneRolesMember: {aiUuid: "${
                                        application.aiUuid
                                    }", atName: "${taskKey}", omUuid: "${_item}", atRona: "${item}", atVenu: "${taskInfo.default}"}}
                                ) { clientMutationId }`;
                        });
                    }
                } else {
                    createOrUpdateTaskMembers += `${"a" + index}:createApplicationTaskSceneRolesMember(
                        input: {applicationTaskSceneRolesMember: {aiUuid: "${application.aiUuid}", atName: "${taskKey}", omUuid: "${
                            values[item]
                        }", atRona: "${item}", atVenu: "${taskInfo.default}"}}
                    ) { clientMutationId }`;
                }
            }
        });
        if (createOrUpdateTaskMembers || deteleTaskMembers) {
            let query = `mutation MyMutation{ ${deteleTaskMembers} ${createOrUpdateTaskMembers} }`;
            res = await graphqlFetch({ query, variables: {} });
            if (res) {
                message.success("成功设置任务角色成员信息");
                await reloadData();
                onCloseGlobalModal();
            }
        }
    };

    return (
        <div style={{ padding: "0 30px" }}>
            {/* {state.selectTaskScene.map((item, index) => (
                <div style={{ marginBottom: 20 }}>
                    <div style={{ marginBottom: 10, fontSize: 14, fontWeight: 600 }}>{item.label}</div>
                    {item.isMany === true && (
                        <Checkbox.Group style={{ width: "100%" }} onChange={(checkedValues) => onChangeMember(checkedValues, index)}>
                            <Row>
                                {state.members.map((item) => (
                                    <Col span={6} key={item.omUuid}>
                                        <Checkbox value={item.omUuid}>{item.omName}</Checkbox>
                                    </Col>
                                ))}
                            </Row>
                        </Checkbox.Group>
                    )}
                    {item.isMany === false && (
                        <Radio.Group style={{ width: "100%" }} onChange={(e) => onChangeMember(e.target.value, index)}>
                            <Row>
                                {state.members.map((item) => (
                                    <Col span={6} key={item.omUuid}>
                                        <Radio value={item.omUuid}>{item.omName}</Radio>
                                    </Col>
                                ))}
                            </Row>
                        </Radio.Group>
                    )}
                </div>
            ))}

            <Divider />
            <div style={{ textAlign: "center" }}>
                <Button theme="solid" onClick={saveRoleMembers}>
                    保存应用角色成员信息
                </Button>
            </div> */}

            <Form name="validate_other" layout="vertical" form={form} onFinish={onFinish}>
                {state.selectTaskScene.map((item, index) => (
                    <>
                        {item.isMany === true && (
                            <Form.Item label={item.label} name={item.label} key={index}>
                                {item.isMany === true && (
                                    <Checkbox.Group style={{ width: "100%" }}>
                                        <Row>
                                            {state.members.map((item) => (
                                                <Col span={6} key={item.omUuid}>
                                                    <Checkbox value={item.omUuid}>{item.omName}</Checkbox>
                                                </Col>
                                            ))}
                                        </Row>
                                    </Checkbox.Group>
                                )}
                            </Form.Item>
                        )}
                        {item.isMany === false && (
                            <Form.Item label={item.label} name={item.label} key={index}>
                                <Radio.Group style={{ width: "100%" }} key={index}>
                                    <Row>
                                        {state.members.map((item) => (
                                            <Col span={6} key={item.omUuid}>
                                                <Radio value={item.omUuid}>{item.omName}</Radio>
                                            </Col>
                                        ))}
                                    </Row>
                                </Radio.Group>
                            </Form.Item>
                        )}
                    </>
                ))}
                <div style={{ textAlign: "center" }}>
                    <Button theme="solid" htmlType="submit" style={{ textAlign: "center" }}>
                        保存应用角色成员信息
                    </Button>
                </div>
            </Form>
        </div>
    );
};

export default SetSceneMembers;
